#include "core/syscall.h"
#include "core/memory.h"
#include "comm/types.h"
#include "core/task.h"
#include "tools/log.h"
#include "fs/fs.h"

// 系统调用处理函数类型，函数指针，用于确定编号和对应函数的关系
typedef int (*syscall_handler_t)(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint32_t arg3);

void sys_print_msg(const char *msg,int arg0){
    log_printf(msg,arg0);
}

static const syscall_handler_t sys_table[]={
    [SYS_msleep]=(syscall_handler_t )sys_sleep,
    [SYS_getpid]=(syscall_handler_t)sys_getpid,
    [SYS_printmsg]=(syscall_handler_t)sys_print_msg,
    [SYS_fork]=(syscall_handler_t)sys_fork,
    [SYS_execve]=(syscall_handler_t)sys_execve,
    [SYS_yield]=(syscall_handler_t)sys_yield,

   
    [SYS_open]=(syscall_handler_t)sys_open,
    [SYS_read]=(syscall_handler_t)sys_read,
    [SYS_write]=(syscall_handler_t)sys_write,
    [SYS_close]=(syscall_handler_t)sys_close,
    [SYS_lseek]=(syscall_handler_t)sys_lseek,

    [SYS_isatty] = (syscall_handler_t)sys_isatty,
	[SYS_sbrk] = (syscall_handler_t)sys_sbrk,
	[SYS_fstat] = (syscall_handler_t)sys_fstat,

    [SYS_dup] = (syscall_handler_t)sys_dup,
};

void do_handler_syscall(syscall_frame_t *frame){
    // 这里是调用门的处理函数，特权级是0,已经经过了切换
    if(frame && frame->func_id< (sizeof(sys_table)/sizeof(syscall_handler_t))){
        syscall_handler_t handler=sys_table[frame->func_id];
        if(handler){
            //调用函数
            int ret=handler(frame->arg0,frame->arg1,frame->arg2,frame->arg3);
            //frame里的eax，充当函数的返回值
            frame->eax=ret;
            return;
        }
    }

    // 不支持的系统调用，打印出错信息
	task_t * task = get_task_current();
	log_printf("task: %s, Unknown syscall: %d", task->name,  frame->func_id);
    frame->eax = -1;  // 设置系统调用的返回值，由eax传递
}; 